<!-- src/views/system/inbounds/detail.vue -->
<template>
  <div class="app-container">
    <el-page-header @back="goBack" :content="title"></el-page-header>

    <el-card class="detail-card">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单名" prop="number">
              <el-input v-model="form.number" placeholder="请输入名称" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人" prop="handledby">
              <el-input v-model="form.handledby" placeholder="请输入处理人" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库时间" prop="finishtime">
              <el-date-picker
                v-model="form.finishtime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择入库时间"
                style="width: 100%"
                :disabled="isViewMode">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">入库单项信息</el-divider>

        <el-row :gutter="10" class="mb8" v-if="!isViewMode">
          <el-col :span="2">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddInboundItems">添加</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteInboundItems" :disabled="checkedInboundItems.length === 0">删除</el-button>
          </el-col>
        </el-row>

        <el-table
          :data="inboundItemsList"
          :row-class-name="rowInboundItemsIndex"
          @selection-change="handleInboundItemsSelectionChange"
          ref="inboundItems"
          border
          class="inbound-items-table">
          <el-table-column type="selection" width="55" align="center" v-if="!isViewMode" />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column label="货物名称" prop="itemName" width="150">
            <template slot-scope="scope">
              <el-select
                v-if="!isViewMode"
                v-model="scope.row.itemName"
                placeholder="请选择货物"
                clearable
                filterable
                @change="(val) => handleGoodsChange(val, scope.row, scope.$index)">
                <el-option
                  v-for="goods in goodsList"
                  :key="goods.id"
                  :label="goods.name"
                  :value="goods.id"
                />
              </el-select>
              <span v-else>{{ scope.row.itemName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="货物编号" prop="itemNumber" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.itemNumber"
                placeholder="请输入货物编号" />
              <span v-else>{{ scope.row.itemNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="货物规格" prop="itemModel" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.itemModel"
                placeholder="请输入货物规格" />
              <span v-else>{{ scope.row.itemModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="货物数量" prop="actualWeight" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.actualWeight"
                placeholder="请输入货物数量" />
              <span v-else>{{ scope.row.actualWeight }}</span>
            </template>
          </el-table-column>
          <el-table-column label="货物单位" prop="itemUnit" width="120">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.itemUnit"
                placeholder="请输入货物单位" />
              <span v-else>{{ scope.row.itemUnit }}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" prop="stockName" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.stockName"
                placeholder="请输入仓库名称" />
              <span v-else>{{ scope.row.stockName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="settlementPrice" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.settlementPrice"
                placeholder="请输入单价"
                @change="(val) => handleamount(val, scope.row, scope.$index)" />
              <span v-else>{{ scope.row.settlementPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="不含税价" prop="excludingPrice">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.excludingPrice"
                placeholder="请输入不含税价" />
              <span v-else>{{ scope.row.excludingPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="含税价" prop="settlementAmount">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.settlementAmount"
                placeholder="请输入含税价" />
              <span v-else>{{ scope.row.settlementAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remarks">
            <template slot-scope="scope">
              <el-input
                v-if="!isViewMode"
                v-model="scope.row.remarks"
                placeholder="请输入备注" />
              <span v-else>{{ scope.row.remarks }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="form-footer" v-if="!isViewMode">
          <el-button type="primary" @click="submitForm" size="medium">保存</el-button>
<!--          <el-button @click="goBack" size="medium">返回</el-button>-->
        </div>
<!--        <div class="form-footer" v-else>-->
<!--          <el-button @click="goBack" size="medium">返回</el-button>-->
<!--        </div>-->
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getInbounds, addInbounds, updateInbounds } from "@/api/system/inbounds";
import {getGoodsInfoList} from "../../../api/system/goodss";

export default {
  name: "InboundsDetail",
  data() {
    return {
      // 页面标题
      title: "",
      // 表单参数
      form: {
        handledby: null,
        reviewer: null,
        reviewTime: null,
        finishtime: null,
        number: null
      },
      // 表单校验规则
      rules: {
        handledby: [
          { required: true, message: "处理人不能为空", trigger: "blur" }
        ],
        number: [
          { required: true, message: "入库单名不能为空", trigger: "blur" }
        ],
        finishtime: [
          { required: true, message: "入库时间不能为空", trigger: "change" }
        ]
      },
      // 入库单项表格数据
      inboundItemsList: [],

      goodsList:[],
      // 子表选中数据
      checkedInboundItems: [],
      // 入库单ID
      id: null,
      // 页面模式（add、edit或view）
      mode: "",
      // 是否为查看模式
      isViewMode: false
    };
  },
  created() {
    // 获取路由参数
    this.id = this.$route.params.id;
    this.mode = this.$route.query.mode || "add";

    // 设置查看模式
    this.isViewMode = this.mode === "view";

    // 设置页面标题
    switch(this.mode) {
      case "add":
        this.title = "新增入库单";
        break;
      case "edit":
        this.title = "编辑入库单";
        break;
      case "view":
        this.title = "查看入库单";
        break;
      default:
        this.title = "入库单详情";
    }

    // 如果是编辑或查看模式，则获取数据
    if ((this.mode === "edit" || this.mode === "view") && this.id && this.id !== 'new') {
      this.getInboundsData(this.id);
    }

    // 获取商品列表（仅在新增或编辑模式下）
    if (this.mode !== "view") {
      this.getGoodsList();
    }
  },
  methods: {
    handleamount(settlementPrice, row, index) {
      this.$set(this.inboundItemsList, index, {
        ...row,
        settlementAmount : settlementPrice * row.actualWeight
      });
    },

    /** 获取商品列表 */
    getGoodsList() {
      // 这里需要替换为实际的API调用
      getGoodsInfoList().then(response => {
        this.goodsList = response.rows
      })
    },

    handleGoodsChange(goodsId, row, index) {
      if (goodsId) {
        // 根据选中的货物ID查找对应的货物信息
        const selectedGoods = this.goodsList.find(goods => goods.id === goodsId);
        if (selectedGoods) {
          // 更新当前行的数据
          this.$set(this.inboundItemsList, index, {
            ...row,
            itemId: selectedGoods.id, // 保存选中的货物ID
            itemName: selectedGoods.name, // 保存选中的货物ID
            itemNumber: selectedGoods.number || '', // 货物编号
            itemModel: selectedGoods.model || '', // 货物规格
            itemUnit: selectedGoods.unit || '', // 货物单位
            stockId: selectedGoods.stockId || '', // 仓库id
            stockName: selectedGoods.stockName || '', // 仓库
          });
        }
      } else {
        // 清空选择时，重置相关字段
        this.$set(this.inboundItemsList, index, {
          ...row,
          itemId: '', // 货物ID清空
          itemName: '', // 货物ID清空
          itemNumber: '', // 货物编号清空
          itemModel: '', // 货物规格清空
          itemUnit: '', // 货物单位清空
          stockId: '', // 货物单位清空
          stockName: '', // 货物单位清空
          excludingPrice: '', // 不含税价清空
          settlementPrice: '' // 含税价清空
        });
      }
    },

    /** 获取入库单详情 */
    getInboundsData(id) {
      getInbounds(id).then(response => {
        this.form = response.data;
        this.inboundItemsList = response.data.inboundItemsList || [];
      });
    },

    /** 返回上一页 */
    goBack() {
      this.$router.go(-1);
    },

    /** 添加入库单项 */
    handleAddInboundItems() {
      const obj = {
        itemName: "",
        itemNumber: "",
        itemModel: "",
        itemUnit: "",
        stockName: "",
        packageType: "",
        finishtime: "",
        remarks: "",
        settlementPrice: "",
        settlementAmount: "",
        actualWeight: "",
        excludingPrice: "",
      };
      this.inboundItemsList.push(obj);
    },

    /** 删除入库单项 */
    handleDeleteInboundItems() {
      if (this.checkedInboundItems.length === 0) {
        this.$message.warning("请先选择要删除的入库单项数据");
        return;
      }

      this.$modal.confirm('是否确认删除选中的入库单项数据？').then(() => {
        const checkedIndexes = this.checkedInboundItems.map(item => item.index);
        this.inboundItemsList = this.inboundItemsList.filter(
          item => !checkedIndexes.includes(item.index)
        );
        this.checkedInboundItems = [];
      }).catch(() => {});
    },

    /** 入库单项序号 */
    rowInboundItemsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 入库单项选择变更 */
    handleInboundItemsSelectionChange(selection) {
      this.checkedInboundItems = selection;
    },

    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查入库单项是否有数据
          if (this.inboundItemsList.length === 0) {
            this.$message.warning("请至少添加一条入库单项数据");
            return;
          }

          // 验证入库单项必填字段
          let validItems = true;
          for (let i = 0; i < this.inboundItemsList.length; i++) {
            const item = this.inboundItemsList[i];
            if (!item.itemName || !item.itemNumber) {
              validItems = false;
              break;
            }
          }

          if (!validItems) {
            this.$message.warning("请完善入库单项必填信息");
            return;
          }

          // 设置入库单项列表
          this.form.inboundItemsList = this.inboundItemsList;

          // 根据模式调用不同接口
          if (this.mode === "edit") {
            updateInbounds(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.goBack();
            });
          } else {
            addInbounds(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.goBack();
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.detail-card {
  margin-top: 20px;
}

.detail-card ::v-deep .el-card__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.detail-card ::v-deep .el-card__body {
  padding: 20px;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.inbound-items-table {
  margin-top: 10px;
}

.form-footer {
  margin-top: 30px;
  text-align: center;
}

.mb8 {
  margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 15px;
  }

  .form-footer {
    margin-top: 20px;
  }
}
</style>
